package org.bug2222.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.bug2222.reggie.common.CustomException;
import org.bug2222.reggie.common.R;
import org.bug2222.reggie.dto.SetmealDto;
import org.bug2222.reggie.entity.Category;
import org.bug2222.reggie.entity.Dish;
import org.bug2222.reggie.entity.Setmeal;
import org.bug2222.reggie.entity.SetmealDish;
import org.bug2222.reggie.mapper.SetmealMapper;
import org.bug2222.reggie.service.CategoryService;
import org.bug2222.reggie.service.DishService;
import org.bug2222.reggie.service.SetmealDishService;
import org.bug2222.reggie.service.SetmealService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {

    @Autowired
    private SetmealDishService setmealDishService;
    @Autowired
    private DishService dishService;
    @Autowired
    private CategoryService categoryService;

    @Override
    @Transactional
    @CacheEvict(value = "setmealCache",allEntries = true)
    public void saveWithDish(SetmealDto setmealDto) {
        //保存套餐的基本信息,insert操作setmeal
        save(setmealDto);

        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        setmealDishes.stream().map((item)->{
            item.setSetmealId(setmealDto.getId());
            return item;
        }).collect(Collectors.toList());

        //保存套餐和菜品的关联信息,insert操作setmeal_dish;
        setmealDishService.saveBatch(setmealDishes);
    }

    /**
     * 删除套餐和菜品的关联数据
     * @param ids
     */
    @Override
    @Transactional
    @CacheEvict(value = "setmealCache",allEntries = true)
    public void removeWithDish(List<Long> ids) {
        //查询套餐状态，确定是否可以删除
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(Setmeal::getId,ids);
        queryWrapper.eq(Setmeal::getStatus,1);
        int count = count(queryWrapper);
        if (count>0) throw new CustomException("套餐正在售卖，不能删除");
        //如果可以删除,先删除套餐表中的数据,setmeal
        removeByIds(ids);

        LambdaQueryWrapper<SetmealDish> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.in(SetmealDish::getSetmealId,ids);
        //删除关系表中的数据,setmeal_dish
        setmealDishService.remove(lambdaQueryWrapper);
    }

    @Override
    public void updateWithStatus(List<Long> ids, int status) {
        if (status==1) {
            LambdaQueryWrapper<SetmealDish> setmealDishLambdaQueryWrapper = new LambdaQueryWrapper<>();
            setmealDishLambdaQueryWrapper.in(SetmealDish::getSetmealId, ids);
            //根据传过来的setmealId集合获得相关联的setmealdish集合
            List<SetmealDish> setmealDishes = setmealDishService.list(setmealDishLambdaQueryWrapper);

            List<Long> dishIds = new ArrayList<>();
            setmealDishes.forEach(item -> {
                //将setmealdish集合中关联的dishId提取出来
                dishIds.add(item.getDishId());
            });
            LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
            dishLambdaQueryWrapper.in(Dish::getId, dishIds);
            //使用提取出来的dishid获得dish集合
            List<Dish> list = dishService.list(dishLambdaQueryWrapper);
            list.forEach(item -> {
                //如果该集合中有菜品是停售状态，则抛出异常
                if (item.getStatus() == 0) throw new CustomException("套餐包含有停售菜品，不能启售");
            });
        }

        LambdaUpdateWrapper<Setmeal> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.in(Setmeal::getId,ids);
        updateWrapper.set(Setmeal::getStatus,status);
        update(updateWrapper);

    }

    @Override
    public Page page(int page, int pageSize, String name) {
        //分页构造器对象
        Page<Setmeal> setmealPage = new Page<>(page, pageSize);
        Page<SetmealDto> setmealDtoPage = new Page<>(page,pageSize);

        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(name != null,Setmeal::getName,name);
        queryWrapper.orderByDesc(Setmeal::getUpdateTime);

        page(setmealPage,queryWrapper);

        BeanUtils.copyProperties(setmealPage,setmealDtoPage,"records");

        List<Setmeal> records = setmealPage.getRecords();

        List<SetmealDto> list =
                records.stream().map((item)->{
                    SetmealDto setmealDto = new SetmealDto();
                    BeanUtils.copyProperties(item,setmealDto);
                    //获得分类id
                    Long categoryId = item.getCategoryId();
                    //根据id查询分类对象
                    Category category = categoryService.getById(categoryId);

                    setmealDto.setCategoryName(category.getName());

                    return setmealDto;
                }).collect(Collectors.toList());

        setmealDtoPage.setRecords(list);
        return setmealDtoPage;
    }

    @Override
    @Cacheable(value = "setmealCache",key = "#setmeal.categoryId + '_' + #setmeal.status")
    public List<Setmeal> list(Setmeal setmeal) {
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(setmeal.getCategoryId()!=null,Setmeal::getCategoryId,setmeal.getCategoryId())
                .eq(setmeal.getStatus()!=null,Setmeal::getStatus,setmeal.getStatus())
                .orderByDesc(Setmeal::getUpdateTime);
        List<Setmeal> setmeals = list(queryWrapper);

        if (setmeals.size()>0)
            return setmeals;

        throw new CustomException("没有找到对应的套餐");
        }

    @Override
    public SetmealDto getByIdWithDish(Long id) {
        // 根据id查询setmeal表中的基本信息
        Setmeal setmeal = this.getById(id);
        SetmealDto setmealDto = new SetmealDto();
        // 对象拷贝。
        BeanUtils.copyProperties(setmeal, setmealDto);
        // 查询关联表setmeal_dish的菜品信息
        LambdaQueryWrapper<SetmealDish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SetmealDish::getSetmealId, id);
        List<SetmealDish> setmealDishList = setmealDishService.list(queryWrapper);
        //设置套餐菜品属性
        setmealDto.setSetmealDishes(setmealDishList);
        return setmealDto;
    }

    @Override
    @Transactional
    public void updateWithDish(SetmealDto setmealDto) {
        // 保存setmeal表中的基本数据。
        this.updateById(setmealDto);
        // 先删除原来的套餐所对应的菜品数据。
        LambdaQueryWrapper<SetmealDish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SetmealDish::getSetmealId, setmealDto.getId());
        setmealDishService.remove(queryWrapper);
        // 更新套餐关联菜品信息。setmeal_dish表。
        // Field 'setmeal_id' doesn't have a default value] with root cause
        // 所以需要处理setmeal_id字段。
        // 先获得套餐所对应的菜品集合。
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        //每一个item为SetmealDish对象。
        setmealDishes = setmealDishes.stream().map((item) -> {
            //设置setmeal_id字段。
            item.setSetmealId(setmealDto.getId());
            return item;
        }).collect(Collectors.toList());

        // 重新保存套餐对应菜品数据
        setmealDishService.saveBatch(setmealDishes);
    }


}

